import { useState } from "react";
type Model<T> = {
  value: T | T[keyof T] | any;
  onChange: (e: any) => void;
  onInput: (e: any) => void;
};
type ResultType<T> = [T, (attr?: string) => Model<T>, (value: T) => void];

export const useModel = <T>(initialValue: T): ResultType<T> => {
  const [value, setValue] = useState<T>(initialValue);
  const model = (attr?: string): Model<T> => {
    const update = (e) => {
      const newValue = e?.target?.value ?? e;
      setValue(attr ? { ...value, [attr]: newValue } : newValue);
    };
    return {
      value: attr ? value[attr] : value,
      onChange: update,
      onInput: update,
    };
  };
  return [value, model, setValue];
};
